package com.tools;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.login.R;

public class LoadListView extends ListView implements AbsListView.OnScrollListener {
    /**
     *  headerView
     */
    private View headerView;
    private int headerViewHeight;
    private ImageView header_iv;
    private ProgressBar header_progress;
    private TextView header_text;
    private TextView header_time;

    /**
     * footerView
     */
    private View footerView;
    private int footerViewHeight;
    private int downY;

    /**
     * footerOverView   用于数据加载完毕添加至listview
     */
    private View footerOverView;

    private final int PULL_REFRESH = 0;//下拉刷新的状态
    private final int RELEASE_REFRESH = 1;//松开刷新的状态
    private final int REFRESHING = 2;//正在刷新的状态

    //当前状态
    private int currentState = PULL_REFRESH;
    //下拉刷新动画
    private RotateAnimation upAnimation,downAnimation;

    private boolean isRefresh = false; //下拉刷新
    private boolean isLoading = false; //上拉加载
    private boolean isLoadOver = false; //数据上拉加载完毕

    public LoadListView(Context context) {
        this(context,null);
    }

    public LoadListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init(){
        setOnScrollListener(this);
        initHeaderView();
        initRotateAnimation();
        initFooterView();
    }


    /**
     * 初始化headerView
     */
    private void initHeaderView() {
        headerView = View.inflate(getContext(), R.layout.header_view, null);
        header_iv = (ImageView) headerView.findViewById(R.id.header_image);
        header_progress = (ProgressBar) headerView.findViewById(R.id.header_progress);
        header_text = (TextView) headerView.findViewById(R.id.header_load_text);
        header_time = (TextView) headerView.findViewById(R.id.header_load_time);

        //测量headView的高度
        headerView.measure(0, 0);
        //获取高度，并保存
        headerViewHeight = headerView.getMeasuredHeight();
        //设置paddingTop = -headerViewHeight;这样，该控件被隐藏
        headerView.setPadding(0, -headerViewHeight, 0, 0);
        //添加头布局
        addHeaderView(headerView);
    }

    /**
     * 初始化footerView
     */
    private void initFooterView() {
        footerView = View.inflate(getContext(), R.layout.footer_view, null);
        footerView.measure(0, 0);
        footerViewHeight = footerView.getMeasuredHeight();
        footerView.setPadding(0, -footerViewHeight, 0, 0);
        addFooterView(footerView);
    }

    /**
     * 初始化footerOverView
     */
    private void initFooterOverView() {
        footerOverView = View.inflate(getContext(), R.layout.footer_over_view, null);
        footerOverView.measure(0, 0);
        addFooterView(footerOverView);
    }

    /**
     * 初始化旋转动画
     */
    private void initRotateAnimation() {

        upAnimation = new RotateAnimation(0, -180,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        upAnimation.setDuration(300);
        upAnimation.setFillAfter(true);

        downAnimation = new RotateAnimation(-180, -360,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        downAnimation.setDuration(300);
        downAnimation.setFillAfter(true);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //获取按下时y坐标
                downY = (int) ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:

                if(currentState==REFRESHING || currentState == RELEASE_REFRESH){
                    super.onTouchEvent(ev);
                    return true;
                }
                //手指滑动偏移量
                int deltaY = (int) (ev.getY() - downY);

                //获取新的padding值
                int paddingTop = -headerViewHeight + deltaY;
                if(paddingTop>-headerViewHeight && getFirstVisiblePosition()==0){
                    //向下滑，且处于顶部，设置padding值，该方法实现了顶布局慢慢滑动显现
                    headerView.setPadding(0, paddingTop, 0, 0);

                    if(paddingTop>=0 && currentState==PULL_REFRESH){
                        //从下拉刷新进入松开刷新状态
                        currentState = RELEASE_REFRESH;
                        refreshHeaderView();
                    }else if (paddingTop<0 && currentState==RELEASE_REFRESH) {
                        //进入下拉刷新状态
                        currentState = PULL_REFRESH;
                        refreshHeaderView();
                    }
                    return true;//拦截TouchMove，不让listview处理该次move事件,会造成listview无法滑动
                }
                break;
            case MotionEvent.ACTION_UP:
                if(currentState==PULL_REFRESH){
                    //仍处于下拉刷新状态，未滑动一定距离，不加载数据，隐藏headView
                    headerView.setPadding(0, -headerViewHeight, 0, 0);
                }else if (currentState==RELEASE_REFRESH) {
                    //显示完整headerView
                    headerView.setPadding(0, 0, 0, 0);
                    currentState = REFRESHING;
                    refreshHeaderView();
                    if(refreshListener != null){
                        refreshListener.onPullRefresh();
                    }
                }
                break;
        }
        return super.onTouchEvent(ev);
    }

    /**
     * 根据currentState来更新headerView
     */
    private void refreshHeaderView(){
        switch (currentState) {
            case PULL_REFRESH:
                header_text.setText("下拉刷新");
                header_progress.setVisibility(View.INVISIBLE);
                header_iv.startAnimation(downAnimation);
                break;
            case RELEASE_REFRESH:
                header_text.setText("松开刷新");
                header_iv.startAnimation(upAnimation);
                break;
            case REFRESHING:
                header_iv.clearAnimation();//因为向上的旋转动画有可能没有执行完
                header_iv.setVisibility(View.INVISIBLE);
                header_progress.setVisibility(View.VISIBLE);
                header_text.setText("正在刷新...");
                break;
        }
    }

    public void setRefreshTime(String time){
        //RefreshTime在“下拉刷新”完成后调用
        header_time.setText("最新：" + time);
        headerView.setPadding(0, -headerViewHeight, 0, 0);
        currentState = PULL_REFRESH;
        refreshHeaderView();
    }

    public void setLoadOver(){
        isLoadOver = true;
    }

    /**
     * 下拉刷新接口及监听方法
     */
    private OnRefreshListener refreshListener;
    public void setOnRefreshListener(OnRefreshListener refreshListener){
        this.refreshListener = refreshListener;
    }
    public interface OnRefreshListener{
        void onPullRefresh();
    }

    /**
     * 上拉加载接口及监听方法
     */
    private OnLoadMoreListener loadMoreListener;
    public void setOnLoadMoreListener(OnLoadMoreListener loadMoreListener){
        this.loadMoreListener = loadMoreListener;
    }
    public interface OnLoadMoreListener{
        void onLoadMore();
    }

    /**
     * SCROLL_STATE_IDLE:闲置状态，就是手指松开
     * SCROLL_STATE_TOUCH_SCROLL：手指触摸滑动，就是按着来滑动
     * SCROLL_STATE_FLING：快速滑动后松开
     */
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if(scrollState==OnScrollListener.SCROLL_STATE_IDLE && getLastVisiblePosition()==(getCount()-1) &&!isLoading &&!isRefresh){
            isLoading = true;
            footerView.setPadding(0, 0, 0, 0);//显示出footerView
            setSelection(getCount());//让listview最后一条显示出来，在页面完全显示出底布局
            if (loadMoreListener!= null && !isLoadOver){
                loadMoreListener.onLoadMore();
            }else if (isLoadOver){
                removeFooterView(footerView);
                initFooterOverView();
            }
        }
    }


    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
    }

}

